import { stringifyObjectContainingErrors, logSection } from './utils/logging'

export let APPLICATION_ERROR_OCCURED = false;

function catchErrors(message, source, lineno, colno, error){
  let fullPayload = JSON.parse(
    stringifyObjectContainingErrors({
      message,
      source,
      lineno,
      colno,
      error
    })
  )

  if(("" + message).indexOf('Script error.') >= 0){
    console.warn('第三方脚本错误: ', message)
    return;
  }
  
  if(("" + message).indexOf('NS_ERROR_FAILURE') >= 0){
    console.warn("Firefox NS_ERROR_FAILURE error: ", message);
    return;
  }

  if(!G_IS_DEV && G_IS_BROWSER && ("" + source).indexOf("shapez") < 0){
    console.warn('第三方错误: ', message)
    return;
  }

  console.log("\n\n\n⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️\n\n\n");
  console.log("          APPLICATION CRASHED             ");
  console.log("\n\n⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️\n\n\n");

  logSection('APPLICATION CRASH', '#e53935');
  console.log('Error:', message, '->', error);
  console.log('Payload:', fullPayload)

  if(APPLICATION_ERROR_OCCURED){
    console.warn('ERROR: Only showing and submitting first error');
    return;
  }

  APPLICATION_ERROR_OCCURED = true;
  const element = document.createElement('div')
  element.id = 'applicationError'

  const title = document.createElement('h1')
  title.innerText = '崩溃!';
  element.appendChild(title)

  const desc = document.createElement('div')
  desc.classList.add('desc')
  desc.innerHTML = `
  程序发生不可挽回的错误。
  你可以将此次奔溃截屏，发送邮箱至 <code>jialecode@qq.com</code>
  `
  element.appendChild(desc)

  const details = document.createElement('pre')
  details.classList.add('details')
  details.innerHTML = (error && error.stack) || message;
  element.appendChild(details)

  const inject = function(){
    if(!G_IS_DEV){
      removeAllChildren(document.body)
    }
    if(document.body.parentElement){
      document.body.parentElement.appendChild(element)
    } else {
      document.body.appendChild(element)
    }
  }

  if(document.body) {
    inject();
  } else {
    setTimeout(() => {
      inject();
    }, 200);
  }

  return true;
}

window.onerror = catchErrors;